<template>
  <div class="table-box">
    <ProTable ref="proTable" title="产品列表" :columns="columns" :data="productList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDrawerStatic(userName, '新增')">新增产品</el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="Setting" @click="toDetail_structure(scope.row)">产品结构</el-button>
        <el-button type="primary" link :icon="EditPen" @click="handleProcessClick(scope.row)">工序流程</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawerStatic(userName, '编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <ProductDrawer ref="drawerRef" @submit="handleSubmit" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="ts" name="useProTable">
import { ref, onMounted } from "vue";
import { Product } from "@/api/interface";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Setting } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import ProductDrawer from "@/views/proTable/components/ProductDrawer.vue";
import axios from "axios";
const router = useRouter();
const proTable = ref<ProTableInstance>();
const baseUrl = import.meta.env.VITE_BASE_URL;

const productList = ref();
/**当前用户信息 */
const userName = ref("");
/**打开详细结构信息 */
const toDetail_structure = (row: any) => {
  router.push({
    path: `/basicData/productConfig/product/detail_structure/${row.id}`
  });
};

/**打开详细工序信息 */
const handleProcessClick = (row: any) => {
  // router.push({
  //   path: `/basicData/productConfig/product/detailProcess/${row.id}` // 使用完整路径
  // });
  router.push({
    path: `/basicData/productConfig/product/assembleProcess/${row.id}` // 使用完整路径
  });
};

onMounted(() => {
  initFormData();
});

const initFormData = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const userId = Number(userInfo.id) || 0; // 如果没有 id，则使用默认值 0
    //数据库
    const response = await axios.post(baseUrl + "/api/carbon/getAllProducts", {
      userId: userId
    });
    console.log("响应数据_读取产品列表:", response.data);
    if (response.data && response.data.code === 200) {
      productList.value = response.data.data;
      console.log("产品列表:", productList.value);
    } else {
      // 处理后端返回的错误信息
      const errorMsg = response.data.msg || "获取产品列表失败";
      console.error("获取产品列表错误:", errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("获取产品列表出错:", error);
    ElMessage.error("获取产品列表失败，可能是因为参数错误或网络问题");
  }
};

// 表格配置项
const columns: ColumnProps<Product.ResProduct>[] = [
  { type: "selection", fixed: "left", width: 80 }, // 多选列
  {
    prop: "productId",
    label: "产品编号",
    search: { el: "input" } // 搜索框
  },
  {
    prop: "productName",
    label: "产品名称",
    search: { el: "input" } // 搜索框
  },
  {
    prop: "description",
    label: "产品描述",
    width: 400
  },
  {
    prop: "createTime",
    label: "创建时间",
    width: 180,
    search: {
      el: "date-picker", // 日期选择器
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" }, // 配置为时间区间
      defaultValue: ["2023-01-01 00:00:00", "2023-12-31 23:59:59"]
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 400 } // 操作列
];

//删除静态数组
const deleteAccount = async (params: Product.ResProduct) => {
  ElMessageBox.confirm("是否删除该项?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning", // 使用字符串形式的类型
    draggable: true
  })
    .then(async () => {
      // 行索引
      const index = productList.value.findIndex((item: any) => item.id === params.id);
      if (index !== -1) {
        try {
          const response = await axios.post(baseUrl + "/api/carbon/deleteProduct", {
            id: params.id
          });
          if (response.data && response.data.code === 200) {
            ElMessage({
              type: "success",
              message: "删除产品成功!"
            });
            await initFormData(); // 删除成功后刷新列表
          } else {
            ElMessage.error(response.data.msg || "删除失败");
          }
        } catch (error: any) {
          console.error("删除产品出错:", error);
          // 检查是否是 409 冲突状态码
          if (error.response && error.response.status === 409) {
            ElMessage({
              type: "warning",
              message: error.response.data?.msg || "该产品正在被项目使用，无法删除"
            });
          } else {
            ElMessage.error("删除产品失败，可能是因为参数错误或网络问题");
          }
        }
      }
    })
    .catch(() => {
      // 如果用户取消了操作，则不做任何处理
    });
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof ProductDrawer> | null>(null);

// 静态方法（操作静态数组）
const openDrawerStatic = (owner: string, title: string, row: Partial<Product.ResProduct> = {}) => {
  // 定义静态操作
  const params = {
    owner,
    title,
    isView: title === "查看",
    row: { ...row } // 静态模式下仅操作此行数据
  };
  drawerRef.value?.acceptParams(params);
};

const handleSubmit = async () => {
  await initFormData(); // 提交后刷新列表
};
</script>
